package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description：TODO 吐槽业务控制层
 * @Author: liulei
 * @Date: 2019年10月22日
 * @Version: V1.0
 **/
@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询全部
     */
    @GetMapping
    public Result findAll(){
        List<Spit> list = spitService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{spitId}")
    public Result findById(@PathVariable String spitId){
        Spit spit = spitService.findById(spitId);
        return new Result(true, StatusCode.OK, "查询成功", spit);
    }

    /**
     * 保存
     */
    @PostMapping
    public Result save(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.OK, "保存成功");
    }

    /**
     * 修改
     */
    @PutMapping("/{spitId}")
    public Result update(@PathVariable String spitId, @RequestBody Spit spit){
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 保存
     */
    @DeleteMapping("/{spitId}")
    public Result deleteById(@PathVariable String spitId){
        spitService.deleteById(spitId);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 根据上级ID查询吐槽数据
     */
    @GetMapping("/comment/{parentid}/{page}/{size}")
    public Result findByParentid(@PathVariable String parentid, @PathVariable int page, @PathVariable int size){
        Page<Spit> spitPage = spitService.findByParentid(parentid, page, size);
        long total = spitPage.getTotalElements();
        List<Spit> spits = spitPage.getContent();
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<>(total, spits));
    }

    /**
     * 吐槽点赞
     */
    @PutMapping("/thumbup/{spitId}")
    public Result updateThumbup(@PathVariable String spitId){
        //判断当前用户是否已经点赞，没有做用户登录认真，先将userid写死
        String userid = "123456";
        //1.判断当前用户是否已经点赞过
        if(redisTemplate.opsForValue().get("thumbup_" + userid) != null){
            return new Result(false, StatusCode.REPERROR, "不能重复点赞");
        }
        spitService.updateThumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_" + userid, userid);
        return new Result(true, StatusCode.OK, "点赞成功");
    }
}
